//
//  LoanDebtDetailViewController.m
//  Wallets Manager
//
//  Created by MAC on 10/31/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "LoanDebtDetailViewController.h"

@interface LoanDebtDetailViewController ()

@end

@implementation LoanDebtDetailViewController
@synthesize pageViewController;
@synthesize dateHeaderLabel;
@synthesize monthViewCalendar;
@synthesize pickerViewPopup;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tabBarController.tabBar.hidden = YES;
    
    //----------Set Current Mode Of View--------------------------------//
    currentMode = 1;
    
    //------------------Init firt page day == today ---------------//
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *date = [NSDate date];
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                     fromDate:date];
    [comps setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    today = [cal dateFromComponents:comps];
    
    //-------------------Set date header to standard-----------------------------//
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    dateHeaderLabel.text = [dateFormatter stringFromDate:today];
    
    //-------------------Init Segment Control---------------------//
    SVSegmentedControl *grayRC = [[SVSegmentedControl alloc] initWithSectionTitles:[NSArray arrayWithObjects:@"Time Mode", @"Daily",@"Category ", nil]];
    [grayRC addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    
	grayRC.font = [UIFont boldSystemFontOfSize:12];
	grayRC.titleEdgeInsets = UIEdgeInsetsMake(0, 14, 0, 14);
	grayRC.height = 30;
    grayRC.selectedIndex = 1;
	
	grayRC.thumb.tintColor = [UIColor colorWithRed:0 green:0.5 blue:0.1 alpha:1];
	
	[self.view addSubview:grayRC];
    [self.view bringSubviewToFront:grayRC];
	
	grayRC.center = CGPointMake(160,430);
    
    //-------------------Init Page View Controller-----------//
    self.pageViewController = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pageViewController.delegate = self;
    self.pageViewController.dataSource = self;
    self.pageViewController.view.frame = CGRectMake(0, 40, 320, 371);
    
    LoDeContentViewController *lodeContentView = [[LoDeContentViewController alloc]init];
    lodeContentView.currentDate = today;
    [self.pageViewController setViewControllers:[NSArray arrayWithObject:lodeContentView] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    [self addChildViewController:pageViewController];
    [self.view addSubview:pageViewController.view];
    
    [self.pageViewController didMoveToParentViewController:self];
    
    //---------------------------NSNotification Center----------------------//
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewLoanPressed :) name:@"alertViewLoanPressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewDebtPressed :) name:@"alertViewDebtPressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loanAdded : ) name:@"loanAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(debtAdded : ) name:@"debtAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loanCompleted : ) name:@"loanCompleted" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(debtCompleted : ) name:@"debtCompleted" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"alertViewLoanPressed" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"alertViewDebtPressed" object:nil];
}

- (void)viewDidUnload
{
    [self setDateHeaderLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)segmentedControlChangedValue:(SVSegmentedControl *)segmentedControl {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    
    if(segmentedControl.selectedIndex == 0) {
        alert = [[BBAlertView alloc]initWithTitle:@"Time Mode" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        
        UIButton *dayModeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        dayModeButton.frame = CGRectMake(10, 50, 128, 43);
        dayModeButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [dayModeButton setTitle:@"Day" forState:UIControlStateNormal];
        [dayModeButton addTarget:self action:@selector(dayModeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:dayModeButton];
        
        UIButton *customModeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        customModeButton.frame = CGRectMake(145, 50, 128, 43);
        customModeButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [customModeButton setTitle:@"Custom" forState:UIControlStateNormal];
        [customModeButton addTarget:self action:@selector(customModeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:customModeButton];
        
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelButton.frame = CGRectMake(10, 103, 263, 43);
        cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Long.png"]];
        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:cancelButton];
        
        [alert show];
        
        
    } else if(segmentedControl.selectedIndex == 1) {
        LoDeContentViewController *currentPage = [pageViewController.viewControllers objectAtIndex:0];
        currentPage.isCategoryMode = NO;
        [currentPage reloadDailyTable];
        
        //Set Header Label
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
        dateHeaderLabel.text = [dateFormatter stringFromDate:today];
        
        //Enable page scroll
        for (UIGestureRecognizer *gr in [self.pageViewController gestureRecognizers]) {
            [gr setEnabled:YES];
        }
        
    } else {
        LoDeContentViewController *currentPage = [pageViewController.viewControllers objectAtIndex:0];
        currentPage.isCategoryMode = YES;
        [currentPage reloadTableByCategory];
    }
}

#pragma mark ------------IBAction---------------
- (IBAction)backButtonPressed:(id)sender {
    //self.hidesBottomBarWhenPushed = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadLoanDebtFromDetail" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (IBAction)addButtonPressed:(id)sender {
    alertView = [[CustomLoDeAlertView alloc]initWithNibName:@"CustomLoDeAlertView" bundle:nil];
    
    [self.view addSubview:alertView.view];
    NSLog(@"%@", [self.view subviews]);
}

#pragma mark - UIPageViewControllerDataSource Methods

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(UIViewController *)viewController
{
    
    LoDeContentViewController *loDeContentViewController = [[LoDeContentViewController alloc] init];
    today = [today dateByAddingTimeInterval:-60*60*24];
    
    loDeContentViewController.currentDate =  today;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    dateHeaderLabel.text = [dateFormatter stringFromDate:loDeContentViewController.currentDate];
    return loDeContentViewController;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(UIViewController *)viewController
{
    LoDeContentViewController *loDeContentViewController = [[LoDeContentViewController alloc] init];
    today = [today dateByAddingTimeInterval:60*60*24];
    
    
    loDeContentViewController.currentDate =  today;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    dateHeaderLabel.text = [dateFormatter stringFromDate:loDeContentViewController.currentDate];
    return loDeContentViewController;
}

#pragma mark - UIPageViewControllerDelegate Methods

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
                   spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    if(UIInterfaceOrientationIsPortrait(orientation))
    {
        //Set the array with only 1 view controller
        UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
        NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
        
        //Important- Set the doubleSided property to NO.
        self.pageViewController.doubleSided = NO;
        //Return the spine location
        return UIPageViewControllerSpineLocationMax;
    }
    else
    {
        //        NSArray *viewControllers = nil;
        //        ContentViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
        //
        //        NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)currentViewController labelContents]];
        //        if(currentIndex == 0 || currentIndex %2 == 0)
        //        {
        //            UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
        //            viewControllers = [NSArray arrayWithObjects:currentViewController, nextViewController, nil];
        //        }
        //        else
        //        {
        //            UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
        //            viewControllers = [NSArray arrayWithObjects:previousViewController, currentViewController, nil];
        //        }
        //        //Now, set the viewControllers property of UIPageViewController
        //        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
        
        return UIPageViewControllerSpineLocationMid;
    }
}

#pragma mark - Notification Center Delegate
- (void) alertViewLoanPressed : (NSNotification *) notification {
    AddLoanViewController *addLoanViewController = [[AddLoanViewController alloc]init];
    addLoanViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addLoanViewController animated:YES];
}

- (void) alertViewDebtPressed : (NSNotification *) notification {
    AddDebtViewController *addDebtViewController = [[AddDebtViewController alloc]init];
    addDebtViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addDebtViewController animated:YES];
}

-(void)loanAdded : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has added successfully!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)debtAdded : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has added successfully!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)loanCompleted : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has completed!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)debtCompleted : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has completed!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}


#pragma mark - ----------------Action Delegate--------------------
-(void)dayModeButtonPressed :(id)sender {
    currentMode = 1;
    [alert dismissWithClickedButtonIndex:0 animated:YES];
    for (UIGestureRecognizer *gr in [self.pageViewController gestureRecognizers]) {
        [gr setEnabled:YES];
    }
    
    LoDeContentViewController *currentPage = [pageViewController.viewControllers objectAtIndex:0] ;
    currentPage.isCategoryMode = NO;
    [currentPage reloadDailyTable];
    
    //Set date Header
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    dateHeaderLabel.text = [dateFormatter stringFromDate:today];
}

-(void)customModeButtonPressed :(id) sender {
    currentMode = 0;
    [alert dismissWithClickedButtonIndex:0 animated:YES];
    [self createDatePickerView];
    for (UIGestureRecognizer *gr in [self.pageViewController gestureRecognizers]) {
        [gr setEnabled:NO];
    }
    
    
    
    //    InExContentViewController *currentPage = [pageViewController.viewControllers objectAtIndex:0];
    //    [currentPage reloadCustomDateTable];
}

-(void)cancelButtonPressed :(id)sender {
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}


#pragma mark --------------------Month Calendar-----------------------
- (void) createDatePickerView {
    
    if(pickerViewPopup == nil)
    {
        pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        
        [pickerViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        //    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
        //    datePickerView.datePickerMode = UIDatePickerModeDate;
        //    datePickerView.hidden = NO;
        //    datePickerView.date = [NSDate date];
        //    [datePickerView addTarget:self action:@selector(datePickerValueChanged :) forControlEvents:UIControlEventValueChanged];
        
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
        
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
        
        //        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        //        [barItems addObject:flexSpace];
        //
        //        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
        //        [barItems addObject:cancelBtn];
        
        [pickerToolbar setItems:barItems animated:YES];
        
        if(monthViewCalendar == nil)
        {
            monthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            monthViewCalendar.delegate  = self;
            monthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [monthViewCalendar reload];
        }
        [monthViewCalendar setFrame:CGRectMake(0, 44, 320, monthViewCalendar.bounds.size.height)];
        pickerViewPopup.clipsToBounds=YES;
        
        //[pickerViewPopup addSubview:datePickerView];
        
        [pickerViewPopup addSubview:pickerToolbar];
        [pickerViewPopup addSubview:monthViewCalendar];
        [pickerViewPopup setBounds:CGRectMake(0, 0, 320, 460)];
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
        
        //[self popUpRefreshFrame];
        
    }else
    {
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
    }
    
}

-(void)popUpRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    
    pickerViewPopup.clipsToBounds=YES;
    [pickerViewPopup setFrame:CGRectMake(0.0, 460 - monthViewCalendar.bounds.size.height - 44, 320, monthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
    
    
}

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	return nil;
}

-(void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
{
    tempDate = date;
}

- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated
{
    //NSLog(@"FRAME = %f X %f", monthView.frame.size.width , monthView.frame.size.height);
    [self performSelector:@selector(popUpRefreshFrame)];
}

-(void)doneDateButtonPressed:(id)sender{
    
    if(!isCalendarShowSecondTime) {
        startDate = tempDate;
        isCalendarShowSecondTime = YES;
        [self createDatePickerView];
    } else {
        endDate = tempDate;
        [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
        isCalendarShowSecondTime = NO;
        
        LoDeContentViewController *currentPage = [pageViewController.viewControllers objectAtIndex:0] ;
        currentPage.startDate = startDate;
        currentPage.endDate   = endDate;
        currentPage.isCategoryMode = NO;
        [currentPage reloadCustomDateTable];
        
        //Set Date Header
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
        dateHeaderLabel.text = [NSString stringWithFormat:@"%@-%@",[dateFormatter stringFromDate:startDate],[dateFormatter stringFromDate:endDate]];
    }
}

@end
